package com.hcc.flow.server.controller.sys;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcc.flow.server.annotation.LogAnnotation;
import com.hcc.flow.server.annotation.Original;
import com.hcc.flow.server.common.enums.UseStatusType;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.page.table.PageTableHandler;
import com.hcc.flow.server.common.page.table.PageTableRequest;
import com.hcc.flow.server.common.page.table.PageTableResponse;
import com.hcc.flow.server.common.utils.AssembleUtil;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.dao.sys.OrgDao;
import com.hcc.flow.server.dao.sys.PermissionDao;
import com.hcc.flow.server.dao.sys.RoleDao;
import com.hcc.flow.server.dto.sys.RoleDto;
import com.hcc.flow.server.model.common.LoginUser;
import com.hcc.flow.server.model.sys.Role;
import com.hcc.flow.server.service.sys.RoleService;
import com.hcc.flow.server.utils.CheckIdUtil;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.sys.OrgOneVO;
import com.hcc.flow.server.vo.sys.RoleOneVO;
import com.hcc.flow.server.vo.sys.RoleVO;
import com.hcc.flow.server.where.sys.RoleWhere;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 角色相关接口
 * 
 * @author 韩长长 
 *
 */
@Api(tags = "角色")
@RestController
@RequestMapping("/roles")
public class RoleController {

	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private PermissionDao permissionDao;
	@Autowired
	private OrgDao orgDao;
	@LogAnnotation
	@PostMapping
	@ApiOperation(value = "角色-保存角色")
	//@PreAuthorize("hasAuthority('sys:role:add')")
	public ApiResult<?> saveRole(@RequestBody RoleDto roleDto) {
		ApiResult<?> apiResult =verifyForm(roleDto);// 校验数据
		if(apiResult != null){
			return apiResult;
		}
		return roleService.saveRole(roleDto);
	}

	@PostMapping("/list")
	@ApiOperation(value = "角色-角色列表")
	//@PreAuthorize("hasAuthority('sys:role:query')")
	public PageInfo<RoleVO> LogListNew(@RequestBody RoleWhere strCon) {
		return roleService.findAllRoles(strCon);
	}

	@GetMapping
	@ApiOperation(value = "角色列表-html版本")
	@Original
	public PageTableResponse LogListNew(PageTableRequest  strCon) {
		RoleWhere where = new RoleWhere(strCon);
		//userService.setOrgIdAndRoleIds(where,"sys:role:query");
		PageHelper.startPage(where.getOffset(), where.getLimit());
		if (StringUtilsV2.isBlank(where.getSqlOrder())) {
			where.setSqlOrder("t.create_time desc");
		}
		PageHelper.orderBy(where.getSqlOrder());
		List<RoleVO> list = roleDao.RoleList(where);
		PageInfo<RoleVO> result =  new PageInfo<RoleVO>(list);
		return new PageTableHandler(new PageTableHandler.CountHandler() {
			@Override
			public int count(PageTableRequest request) {
				return CommUtil.null2Int(result.getTotal());
			}
		}, new PageTableHandler.ListHandler() {
			@Override
			public List<RoleVO> list(PageTableRequest request) {
				return result.getList();
			}
		}).handle(strCon);
		//return PageInfo<SysLogs> list = sysLogService.findAllLogs(new LogWhere(strCon));
	}
	
	@GetMapping("/org/{id}")
	@ApiOperation(value = "角色-根据机构id获取机构下面所有角色")
	public ApiResult<?> getRolesByOrgId(@PathVariable String id) {
		if(StringUtilsV2.isBlank(id)){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(roleDao.getRolesByOrgId(id));
	}
	@PostMapping("/org")
	@ApiOperation(value = "角色-根据机构ids获取机构下面所有角色")
	public ApiResult<?> getRolesByOrgIds(@RequestBody List<String> ids) {
		if(CollectionUtils.isEmpty(ids)){
			return ApiResult.error("要查询的orgIds不能为空");
		}
    	return ApiResult.data(AssembleUtil.selectCheck(roleDao.getRolesByOrgIds(StringUtilsV2.join(ids,","))));
	}
	@GetMapping("/{id}")
	@ApiOperation(value = "角色-根据id获取角色")
	//@PreAuthorize("hasAuthority('sys:role:query')")
	public ApiResult<?> get(@PathVariable String id) {
		if(StringUtilsV2.isBlank(id)){
			return ApiResult.error("要查询的id不能为空");
		}
		RoleOneVO role = roleDao.getById(id);
		if (role != null) {
			//角色用户的菜单权限
			List<String> pids = permissionDao.selectPermissionIdsByRoleId(role.getRoleId());
			role.setPermissionIds(pids);
			//角色对应父角色信息
			String parentId = role.getParentId();
			String parentName = role.getParentName();
			List<String> ids = new ArrayList<String>();
			List<String> names = new ArrayList<String>();
			while (StringUtilsV2.isNotBlank(parentId) && !"0".equals(parentId)) {
				ids.add(parentId);
				names.add(parentName);
				RoleOneVO roleW = roleDao.getById(parentId);
				if(roleW != null){
					parentId = roleW.getParentId();
					parentName = roleW.getParentName();
				}
			}
			Collections.reverse(ids);
			Collections.reverse(names);
			role.setParentIds(ids);
			role.setParentNames(names);
			//角色所属机构信息
			OrgOneVO org = orgDao.getById(role.getOrgId());
			if(org != null){
				String parentOrgId = org.getOrgId();
				String parentOrgName = org.getOrgName();
				List<String> orgIds = new ArrayList<String>();
				List<String> orgNames = new ArrayList<String>();
				while (!"0".equals(parentOrgId)) {
					orgIds.add(parentOrgId);
					orgNames.add(parentOrgName);
					OrgOneVO orgW = orgDao.getById(parentOrgId);
					if(orgW != null){
						parentOrgId = orgW.getParentId();
						parentOrgName = orgW.getParentName();
					}
				}
				Collections.reverse(orgIds);
				Collections.reverse(orgNames);
				role.setParentOrgIds(orgIds);
				role.setParentOrgNames(orgNames);
			}
			
		}
		return ApiResult.data(role);
	}

	@GetMapping("/all")
	@ApiOperation(value = "角色-所有角色")
	//@PreAuthorize("hasAnyAuthority('sys:user:query','sys:role:query')")
	public List<Role> roles() {
		return roleDao.listAll();
	}

	@GetMapping(params = "userId")
	@ApiOperation(value = "角色-根据用户id获取拥有的角色")
	//@PreAuthorize("hasAnyAuthority('sys:user:query','sys:role:query')")
	public ApiResult<?> roles(String userId) {
		if(StringUtilsV2.isBlank(userId)){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(roleDao.listByUserId(userId));
	}

	@LogAnnotation
	@DeleteMapping("/delete/{id}")
	@ApiOperation(value = "角色-物理删除")
	//@PreAuthorize("hasAuthority('sys:role:del')")
	public ApiResult<?> delete(@PathVariable String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("ID不能为空");
		}
		if(id.equals("1") || id.equals("2")){
			return ApiResult.error("系统角色不能删除");
		}
		//系统数据检测
		ApiResult<?> checkAr = CheckIdUtil.checkId(Arrays.asList("1","2","3"), id);
		if(!checkAr.isSuccess()){
			return checkAr;
		}
		Role deleteRole = roleDao.getByRoleId(id);
		if(deleteRole == null){
			return ApiResult.error("要删除的角色数据不存在");
		}
		LoginUser user = UserUtil.getLoginUser();
		List<String> userRoleIds = roleDao.getListRoleIdsByUserId(user.getUserId());
		if(userRoleIds.contains(id)){
			return ApiResult.error("用户不能删除自己拥有的角色");
		}
		int userMinlevel = roleDao.getMinLevelByRoleIds(user.getUserId());
		if(user.getOrgId().equals(deleteRole.getOrgId()) && deleteRole.getLevel().intValue() >= userMinlevel){
			return ApiResult.error("用户不能删除自己机构同级或比自己更高级别的角色");
		}
		//下面有子角色
		int childRoleCount = roleDao.countByParendId(id);
		if(childRoleCount > 0){
			return ApiResult.error("不能删除该角色，该角色下面有"+childRoleCount+"个子角色");
		}
		//下面有用户
		int userCount = roleDao.countUserByRoleId(id);
		if(userCount > 0){
			return ApiResult.error("不能删除该角色，该角色下面有"+userCount+"个用户");
		}
		//下面有菜单
		int permissionCount = roleDao.countPermissionByRoleId(id);
		if(permissionCount > 0){
			return ApiResult.error("不能删除该角色，该角色下面有"+permissionCount+"个菜单权限");
		}
		roleService.deleteRole(id);
		return ApiResult.ok();
	}

	@LogAnnotation
	@DeleteMapping("/{id}")
	@ApiOperation(value = "角色-逻辑删除")
	//@PreAuthorize("hasAuthority('sys:role:del')")
	public ApiResult<?> deleteEditStatus(@PathVariable String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("ID不能为空");
		}
		if(id.equals("1") || id.equals("2")){
			return ApiResult.error("系统角色不能删除");
		}
		//系统数据检测
		ApiResult<?> checkAr = CheckIdUtil.checkId(Arrays.asList("1","2","3"), id);
		if(!checkAr.isSuccess()){
			return checkAr;
		}
		Role deleteRole = roleDao.getByRoleId(id);
		if(deleteRole == null){
			return ApiResult.error("要删除的角色数据不存在");
		}
		LoginUser user = UserUtil.getLoginUser();
		List<String> userRoleIds = roleDao.getListRoleIdsByUserId(user.getUserId());
		if(userRoleIds.contains(id)){
			return ApiResult.error("用户不能删除自己拥有的角色");
		}
		int userMinlevel = roleDao.getMinLevelByRoleIds(user.getUserId());
		if(user.getOrgId().equals(deleteRole.getOrgId()) && deleteRole.getLevel().intValue() >= userMinlevel){
			return ApiResult.error("用户不能删除自己机构同级或比自己更高级别的角色");
		}
		//下面有子角色
		int childRoleCount = roleDao.countByParendId(id);
		if(childRoleCount > 0){
			return ApiResult.error("不能删除该角色，该角色下面有"+childRoleCount+"个子角色");
		}
		//下面有用户
		int userCount = roleDao.countUserByRoleId(id);
		if(userCount > 0){
			return ApiResult.error("不能删除该角色，该角色下面有"+userCount+"个用户");
		}
		//下面有菜单
		int permissionCount = roleDao.countPermissionByRoleId(id);
		if(permissionCount > 0){
			return ApiResult.error("不能删除该角色，该角色下面有"+permissionCount+"个菜单权限");
		}
		roleDao.updateStatus(Arrays.asList(id), UseStatusType.DELETE.getCode());
		// roleDao.deleteRolePermission(id);
		roleDao.deleteRoleUser(id);
		return ApiResult.ok();
	}

	/**
	 * 验证参数是否正确
	 */
	private ApiResult<?> verifyForm(RoleDto roleDto) {
		if (roleDto == null) {
			return ApiResult.error("数据不能为空");
		}else if(StringUtilsV2.isBlank(roleDto.getOrgId())){
			return ApiResult.error("角色对应机构Id不能为空");
		}
		if (StringUtilsV2.isBlank(roleDto.getRoleName())) {
			return ApiResult.error("角色名称不能为空");
		}
		// 上级菜单id
		String parentId = roleDto.getParentId();
		// 没传父菜单id默认为顶级菜单
		if (StringUtilsV2.isBlank(parentId) || "0".equals(parentId)) {
			roleDto.setParentId("0");
			// 默认为顶级
			roleDto.setLevel(1);
		} else {
			if(parentId.equals(roleDto.getRoleId())) {
				return ApiResult.error("角色的父角色不能是自己");
			}
			RoleDto parentOrg = roleDao.getById(parentId);
			Integer parentLevel = parentOrg.getLevel();
			if (parentLevel != null) {
				roleDto.setLevel(parentLevel + 1);
			}
		}
		return null;
	}
}
